package com.cheng.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chengjunjie
 * @date 2025-10-10
 */

public class ApplicationContext {

    private Class configClass;
    // bean定义
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    // 单例池
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
    // 处理器
    private ArrayList<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public ApplicationContext(Class configClass) {
        this.configClass = configClass;

        // 1、扫描路径
        if (configClass.isAnnotationPresent(ComponentScan.class)) {

            ComponentScan componentScan = (ComponentScan) configClass.getAnnotation(ComponentScan.class);

            // 扫描路径 com.cheng.service -> com/cheng/ service
            String path = componentScan.value();
            path = path.replace(".", "/");

            // /Users/huace/IdeaProjects00/spring-test/out/production/spring-test/com/cheng/service
            ClassLoader classLoader = ApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);

            assert resource != null;
            File file = new File(resource.getFile());
            if (file.isDirectory()) {
                File[] files = file.listFiles();

                assert files != null;
                for (File f : files) {

                    String fileName = f.getAbsolutePath();
                    if (fileName.endsWith(".class")) {

                        String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                        className = className.replace("/", ".");

                        try {
                            Class<?> aClass = classLoader.loadClass(className);
                            if (aClass.isAnnotationPresent(Component.class)) {

                                if (BeanPostProcessor.class.isAssignableFrom(aClass)) {
                                    BeanPostProcessor beanPostProcessor = (BeanPostProcessor) aClass.newInstance();
                                    beanPostProcessorList.add(beanPostProcessor);
                                }

                                Component component = aClass.getAnnotation(Component.class);
                                String beanName = component.value();

                                if ("".equals(beanName)) {
                                    beanName = Introspector.decapitalize(aClass.getSimpleName());
                                }

                                BeanDefinition beanDefinition = getBeanDefinition(aClass);

                                beanDefinitionMap.put(beanName, beanDefinition);
                            }
                        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }

        // 2、实例化单例bean
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);

            if ("singleton".equals(beanDefinition.getScope())) {
                Object object = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, object);
            }

        }
    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();
        try {
            Object instance = clazz.getConstructor().newInstance();

            // 1、简单版依赖注入
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    field.set(instance, getBean(field.getName()));
                }
            }

            // 2、aware 回调把beanName传给aware接口的实现类
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            // 3、BeanPostProcessor 创建实例前
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }

            // 4、初始化
            if (instance instanceof InitializeBean) {
                ((InitializeBean) instance).afterPropertiesSet();
            }

            // 5 、BeanPostProcessor 创建实例后
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }
            return instance;
        } catch (InstantiationException | InvocationTargetException | NoSuchMethodException |
                 IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private static BeanDefinition getBeanDefinition(Class<?> aClass) {
        BeanDefinition beanDefinition = new BeanDefinition();
        if (aClass.isAnnotationPresent(Scope.class)) {
            Scope scope = aClass.getAnnotation(Scope.class);
            beanDefinition.setScope(scope.value());
        } else {
            beanDefinition.setScope("singleton");
        }
        beanDefinition.setType(aClass);
        return beanDefinition;
    }

    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);

        if (beanDefinition != null) {
            String scope = beanDefinition.getScope();
            if ("singleton".equals(scope)) {
                Object bean = singletonObjects.get(beanName);
                if (bean == null) {
                    Object o = createBean(beanName, beanDefinition);
                    singletonObjects.put(beanName, o);
                }
                return bean;
            } else {
                return createBean(beanName, beanDefinition);
            }
        } else {
            throw new NullPointerException();
        }
    }
}
